package cn.org.channl.server.handler;

import cn.org.channl.message.Message;
import cn.org.channl.message.Static;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;
import lombok.extern.slf4j.Slf4j;

/**
 * 整个包长度大小实际依赖messageId字段决定
 */
@Slf4j
public class BaseMessageIdHandler extends ByteToMessageDecoder{

	@Override
	protected void decode(ChannelHandlerContext chc, ByteBuf bytebuf,List<Object> list) {
		if(bytebuf.readableBytes() < 5) {
			return;
		}
		byte[] hdCache = new byte[5];
		bytebuf.markReaderIndex();
		bytebuf.readBytes(hdCache);		
		bytebuf.resetReaderIndex();
		bytebuf.markReaderIndex(); 
		/*bd bd bd bd f0 b9 78 ce 04 60 11 03 00 82 00 22*/
		/*先读4个字节,登陆请求是0xBDBDBDBD,其他请求为token*/
		int  header = bytebuf.readInt();
		/*在读一个字节:messageId*/    
		byte messageId = bytebuf.readByte();
		//到这里已经读取了5个字节
		switch(messageId){ 
			case  Static.MESSAGE_ID_LNK_LIN:    //登陆请求:4+1+10+1个字节才能处理
				if(bytebuf.readableBytes() < 11){					
					bytebuf.resetReaderIndex();
					return;
				}else{
					byte[] payload = new byte[10];
					bytebuf.readBytes(payload);
					//int thisCk = checkSum(hdCache,payload);
					byte clientCK = bytebuf.readByte();
					//if(thisCk == clientCK){    
					Message message = new Message();
					message.setHeader(header);
					message.setMessageId(messageId);
					message.setPayload(payload);
					message.setCk(clientCK);
					list.add(message);
				}
				break;
			default:
				return;
				
		}
		
	}
	
	/**
	 * 校验和 CK
	 * @return
	 */
	public static int checkSum(byte[] header, byte[] body){
		int sum = 0;
		for(int i = 0; i < header.length; i++){
			sum += header[i];			
		}
		for(int i = 0; i < body.length; i++){
			sum += body[i];	
			
		}
		sum = sum % 0x100;
		sum = 0xFF - sum;
		log.info("check sum==============" + sum);
		return sum;
	}
	
	public static int check(byte[] buf){
		int sum = 0;
		for(int i = 0; i < buf.length; i++){
			sum += buf[i];	
			sum = sum % 0x100;
		}
		sum = 0xFF - sum;
		log.info("sum==============" + sum);
		return sum;
	}
	
}
